package com.tqyan.service.executor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @description 论文线程池
 * <p> <功能详细描述> </p>
 *
 * @author 陈晨
 * @date 2023/4/13 19:24
 */
@Configuration
@EnableAsync
public class PaperExecutorConfiguration {

    private static final int CORE_POOL_SIZE = 30;
    private static final int MAX_POOL_SIZE = 50;
    private static final int QUEUE_CAPACITY = 500;
    private static final String NAME_PREFIX = "thread-paper-";

    @Bean(name = "paperExecutor")
    public Executor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 配置核心线程数
        executor.setCorePoolSize(CORE_POOL_SIZE);
        // 配置最大线程数
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        // 配置队列大小
        executor.setQueueCapacity(QUEUE_CAPACITY);
        // 配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(NAME_PREFIX);
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        /**
            AbortPolicy：将抛出RejectedExecutionException
            CallerRunsPolicy：直接在execute方法的调用线程中运行被拒绝的任务。
            DiscardOldestPolicy：放弃最旧的未处理请求，然后重试execute。
            DiscardPolicy：默认情况下它将丢弃被拒绝的任务。
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }

}


